package com.woniu.sharepark.platformsystem.log.interceptor;

import com.woniu.sharepark.common.pojo.Login;
import com.woniu.sharepark.platformsystem.log.annonation.BackgroundLogAnnotation;
import com.woniu.sharepark.platformsystem.log.pojo.Log;
import com.woniu.sharepark.platformsystem.log.util.LogUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 自定义拦截器，用于对controller方法拦截判断是否有log注解，有再调用插入日志方法
 *
 * @author zy
 * @date 2019/6/3 14:50
 */
public class LogInterceptor implements HandlerInterceptor {

    /**
     * 需要logUtil组件，由于没法把logUtil组件直接赋值给拦截器，
     * 所以在配置类加入了注解赋值，再传给拦截器的logUtil属性。
     */
    @Autowired
    private LogUtil logUtil;
    private Login relLogin;
    private Log log;

    private String address;
    /**
     * 预处理回调方法，实现处理器的预处理（如登录检查），第三个参数为响应的处理器（如我们上一章的Controller实现）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*判断是否请求静态页面，是直接返回*/
        try {
            HandlerMethod method = (HandlerMethod) handler;
        } catch (Exception e) {
            return true;
        }

        /*获取ip地理位置,注意不能使用localhost访问*/
        String xIp = request.getHeader("X-Real-IP");
        String xFor = request.getHeader("X-Forwarded-For");
        if (xFor != null && xFor.length() != 0 && !"unknown".equalsIgnoreCase(xFor)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xFor.indexOf(",");
            if (index != -1) {
                xFor = xFor.substring(0, index);
            }
        } else {
            xFor = xIp;
            if (xFor == null || xFor.length() == 0 || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getHeader("Proxy-Client-IP");
            }
            if (xFor == null || xFor.length() == 0 || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getHeader("WL-Proxy-Client-IP");
            }
            if (xFor == null || xFor.length() == 0 || "unknown".equalsIgnoreCase(xFor)) {
                xFor = request.getRemoteAddr();
            }
        }

       /* System.out.println("xfor__________________");
        System.out.println(xFor);*/
       address = xFor;
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    /**
     * 整个请求处理完毕回调方法，即在视图渲染完毕时回调
     * 更改逻辑，没用户时都不插入数据
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        /*排除静态*/
        HandlerMethod method;
        try {
            method = (HandlerMethod) handler;
        } catch (Exception e) {
            return;
        }
        /*日志所需，先从shiro中获取所需用户信息,异常说明没有，则return */
        try {
           /* user = SecurityUtils.getSubject().getPrincipal();*/

            relLogin = (Login) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
            if (relLogin == null) {
                return;
            }
        } catch (Exception e) {
            return;
        }

        /*后台日志*/
        BackgroundLogAnnotation bla = method.getMethodAnnotation(BackgroundLogAnnotation.class);

        if (bla != null) {

            String loOperate = bla.operate();
            Date lTime = new Date();
            int lId = relLogin.getlId();
            int lFlag = 0;
            //System.out.println("lo"+loOperate+":"+lId+":"+lTime+":"+lFlag);

            logUtil.writeBackgroundLog(new Log(loOperate,lId,lTime,address,lFlag));

        }
    }
}
